package com.app.utiles.other;

import android.text.TextUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 身份证工具类
 *
 * @author chenjh
 * @version 1.0, 2010-06-17
 */

public class IdCardUtils {


    /**
     * 每位加权因子
     */
    public static final int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    /**
     * 最低年限
     */
    public static final int MIN = 1930;
    //省份
    public static Map<String, String> provinceCodes = new HashMap<String, String>();
    /**
     * 台湾身份首字母对应数字
     */
    public static Map<String, Integer> twFirstCode = new HashMap<String, Integer>();
    /**
     * 香港身份首字母对应数字
     */
    public static Map<String, Integer> hkFirstCode = new HashMap<String, Integer>();

    static {
        provinceCodes.put("11", "北京");
        provinceCodes.put("12", "天津");
        provinceCodes.put("13", "河北");
        provinceCodes.put("14", "山西");
        provinceCodes.put("15", "内蒙古");
        provinceCodes.put("21", "辽宁");
        provinceCodes.put("22", "吉林");
        provinceCodes.put("23", "黑龙江");
        provinceCodes.put("31", "上海");
        provinceCodes.put("32", "江苏");
        provinceCodes.put("33", "浙江");
        provinceCodes.put("34", "安徽");
        provinceCodes.put("35", "福建");
        provinceCodes.put("36", "江西");
        provinceCodes.put("37", "山东");
        provinceCodes.put("41", "河南");
        provinceCodes.put("42", "湖北");
        provinceCodes.put("43", "湖南");
        provinceCodes.put("44", "广东");
        provinceCodes.put("45", "广西");
        provinceCodes.put("46", "海南");
        provinceCodes.put("50", "重庆");
        provinceCodes.put("51", "四川");
        provinceCodes.put("52", "贵州");
        provinceCodes.put("53", "云南");
        provinceCodes.put("54", "西藏");
        provinceCodes.put("61", "陕西");
        provinceCodes.put("62", "甘肃");
        provinceCodes.put("63", "青海");
        provinceCodes.put("64", "宁夏");
        provinceCodes.put("65", "新疆");
        provinceCodes.put("71", "台湾");
        provinceCodes.put("81", "香港");
        provinceCodes.put("82", "澳门");
        provinceCodes.put("91", "国外");
        twFirstCode.put("A", 10);
        twFirstCode.put("B", 11);
        twFirstCode.put("C", 12);
        twFirstCode.put("D", 13);
        twFirstCode.put("E", 14);
        twFirstCode.put("F", 15);
        twFirstCode.put("G", 16);
        twFirstCode.put("H", 17);
        twFirstCode.put("J", 18);
        twFirstCode.put("K", 19);
        twFirstCode.put("L", 20);
        twFirstCode.put("M", 21);
        twFirstCode.put("N", 22);
        twFirstCode.put("P", 23);
        twFirstCode.put("Q", 24);
        twFirstCode.put("R", 25);
        twFirstCode.put("S", 26);
        twFirstCode.put("T", 27);
        twFirstCode.put("U", 28);
        twFirstCode.put("V", 29);
        twFirstCode.put("X", 30);
        twFirstCode.put("Y", 31);
        twFirstCode.put("W", 32);
        twFirstCode.put("Z", 33);
        twFirstCode.put("I", 34);
        twFirstCode.put("O", 35);
        hkFirstCode.put("A", 1);
        hkFirstCode.put("B", 2);
        hkFirstCode.put("C", 3);
        hkFirstCode.put("R", 18);
        hkFirstCode.put("U", 21);
        hkFirstCode.put("Z", 26);
        hkFirstCode.put("X", 24);
        hkFirstCode.put("W", 23);
        hkFirstCode.put("O", 15);
        hkFirstCode.put("N", 14);
    }

    /**
     * 验证身份证是否合法
     */
    public static boolean validateCard(String idCard) {
        if (TextUtils.isEmpty(idCard)) {
            return false;
        }
        String card = idCard.trim();
        if (isCard18(card)) {
            return true;
        }
        if (isCard15(card)) {
            return true;
        }
        String[] cardval = validateIdCard10(card);
        if (cardval != null) {
            if (cardval[2].equals("true")) {
                return true;
            }
        }
        return false;

    }
    // 1-2位省、自治区、直辖市代码；
    // 3-4位地级市、盟、自治州代码；
    // 5-6位县、县级市、区代码；
    // 7-14位出生年月日，比如19670401代表1967年4月1日；
    // 15-17位为顺序号，其中17位男为单数，女为双数；
    // 18位为校验码，0-9和X，由公式随机产生。

    /**
     * 验证18位身份编码是否合法
     *
     * @param idCard 身份编码
     * @return 是否合法
     */

    private static boolean isCard18(String idCard) {
        boolean isIdCard = false;
        if (TextUtils.isEmpty(idCard) || idCard.length() != 18) {
            return isIdCard;
        }
        // 前17位(应该都是数字)
        String code17 = idCard.substring(0, 17);
        if (!isNumberAll(code17)) {
            return isIdCard;
        }
        int[] idNumber17 = new int[17];
        for (int i = 0; i < code17.length(); i++) {
            idNumber17[i] = NumberUtile.getStringToInt(String.valueOf(code17.charAt(i)), 0);
        }
        //
        int number17 = getIdCardNumber(idNumber17);

        // 获取校验位
        String val = getCheckCode18(number17);
        if (val == null) {

        }
        // 第18位
        String code18 = idCard.substring(17, 18);
        if (TextUtils.isEmpty(code18)) {
            return isIdCard;
        }
        isIdCard = val.equalsIgnoreCase(code18);
        return isIdCard;
    }

    //15位身份证号码各位的含义:
    //1-2位省、自治区、直辖市代码；
    //3-4位地级市、盟、自治州代码；
    //5-6位县、县级市、区代码；
    //7-12位出生年月日,比如670401代表1967年4月1日；
    //13-15位为顺序号，其中15位男为单数，女为双数；

    /**
     * 验证15位身份编码是否合法
     *
     * @param idCard 身份编码
     * @return 是否合法
     */
    public static boolean isCard15(String idCard) {
        boolean isIdCard = false;
        if (TextUtils.isEmpty(idCard) || idCard.length() != 15) {
            return isIdCard;
        }
        if (!isNumberAll(idCard)) {
            return isIdCard;
        }
        String proCode = idCard.substring(0, 2);
        String cityId = provinceCodes.get(proCode);
        if (TextUtils.isEmpty(cityId)) {
            return isIdCard;
        }
        String birthCode = idCard.substring(6, 12);
        Date birthDate = null;
        try {
            birthDate = new SimpleDateFormat("yy").parse(birthCode.substring(0, 2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (birthDate == null) {
            return isIdCard;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(birthDate);
        int month = NumberUtile.getStringToInt(birthCode.substring(2, 4));
        int day = NumberUtile.getStringToInt(birthCode.substring(4, 6));
        if (month > 12 || month < 0) {
            return isIdCard;
        }
        int y = cal.get(Calendar.YEAR);
        isIdCard = isDate(y, month, day);
        return isIdCard;
    }

    /**
     * 将15位身份证号码转换为18位
     *
     * @param idCard 15位身份编码
     * @return 18位身份编码
     */
    public static String card15to18(String idCard) {
        String idCard18 = "";
        boolean isIdCard = isCard15(idCard);
        if (!isIdCard) {
            return idCard18;
        }
        String birthday = idCard.substring(6, 12);
        Date birthDate = null;
        try {
            birthDate = new SimpleDateFormat("yyMMdd").parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(birthDate);
        // 获取出生年(完全表现形式,如：2010)
        String year = String.valueOf(cal.get(Calendar.YEAR));
        idCard18 = idCard.substring(0, 6) + year + idCard.substring(8);
        int[] iCard = new int[idCard18.length()];
        for (int i = 0; i < idCard18.length(); i++) {
            iCard[i] = NumberUtile.getStringToInt(String.valueOf(idCard18.charAt(i)));
        }
        // 获取校验位
        int bumber = getIdCardNumber(iCard);
        String sVal = getCheckCode18(bumber);
        idCard18 += sVal;
        return idCard18;
    }

    //字符串全是数字验证
    private static boolean isNumberAll(String numbers) {
        boolean isNumber = false;
        if (TextUtils.isEmpty(numbers)) {
            return isNumber;
        }
        isNumber = numbers.matches("^[0-9]*$");
        return isNumber;
    }

    /**
     * 验证10位身份编码是否合法
     *
     * @param idCard 身份编码
     * @return 身份证信息数组
     * <p>
     * [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false)
     * 若不是身份证件号码则返回null
     * </p>
     */
    public static String[] validateIdCard10(String idCard) {
        String[] info = new String[3];
        String card = idCard.replaceAll("[\\(|\\)]", "");
        if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) {
            return null;
        }
        if (idCard.matches("^[a-zA-Z][0-9]{9}$")) { // 台湾
            info[0] = "台湾";
            System.out.println("11111");
            String char2 = idCard.substring(1, 2);
            if (char2.equals("1")) {
                info[1] = "M";
                System.out.println("MMMMMMM");
            } else if (char2.equals("2")) {
                info[1] = "F";
                System.out.println("FFFFFFF");
            } else {
                info[1] = "N";
                info[2] = "false";
                System.out.println("NNNN");
                return info;
            }
            info[2] = isTWCard(idCard) ? "true" : "false";
        } else if (idCard.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) { // 澳门
            info[0] = "澳门";
            info[1] = "N";
        } else if (idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) { // 香港
            info[0] = "香港";
            info[1] = "N";
            info[2] = isHKCard(idCard) ? "true" : "false";
        } else {
            return null;
        }
        return info;
    }

    /**
     * 验证台湾身份证号码
     *
     * @param idCard 身份证号码
     * @return 验证码是否符合
     */
    public static boolean isTWCard(String idCard) {
        String start = idCard.substring(0, 1);
        String mid = idCard.substring(1, 9);
        String end = idCard.substring(9, 10);
        Integer iStart = twFirstCode.get(start);
        Integer sum = iStart / 10 + (iStart % 10) * 9;
        char[] chars = mid.toCharArray();
        Integer iflag = 8;
        for (char c : chars) {
            sum = sum + Integer.valueOf(c + "") * iflag;
            iflag--;
        }
        return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.valueOf(end) ? true : false;
    }

    /**
     * 验证香港身份证号码(存在Bug，部份特殊身份证无法检查)
     * <p>
     * 身份证前2位为英文字符，如果只出现一个英文字符则表示第一位是空格，对应数字58 前2位英文字符A-Z分别对应数字10-35
     * 最后一位校验码为0-9的数字加上字符"A"，"A"代表10
     * </p>
     * <p>
     * 将身份证号码全部转换为数字，分别对应乘9-1相加的总和，整除11则证件号码有效
     * </p>
     *
     * @param idCard 身份证号码
     * @return 验证码是否符合
     */
    public static boolean isHKCard(String idCard) {
        String card = idCard.replaceAll("[\\(|\\)]", "");
        Integer sum = 0;
        if (card.length() == 9) {
            sum = (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 9 + (Integer.valueOf(card.substring(1, 2).toUpperCase().toCharArray()[0]) - 55) * 8;
            card = card.substring(1, 9);
        } else {
            sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 8;
        }
        String mid = card.substring(1, 7);
        String end = card.substring(7, 8);
        char[] chars = mid.toCharArray();
        Integer iflag = 7;
        for (char c : chars) {
            sum = sum + Integer.valueOf(c + "") * iflag;
            iflag--;
        }
        if (end.toUpperCase().equals("A")) {
            sum = sum + 10;
        } else {
            sum = sum + Integer.valueOf(end);
        }
        return (sum % 11 == 0) ? true : false;
    }

    /**
     * 将身份证的每位和对应位的加权因子相乘之后，再得到和值
     *
     * @param idNumbers
     * @return 身份证编码。
     */
    private static int getIdCardNumber(int[] idNumbers) {
        int number = 0;
        if (power.length != idNumbers.length) {
            return number;
        }
        for (int i = 0; i < idNumbers.length; i++) {
            for (int j = 0; j < power.length; j++) {
                if (i == j) {
                    number = number + idNumbers[i] * power[j];
                }
            }
        }
        return number;
    }

    /**
     * 将power和值与11取模获得余数进行校验码判断
     *
     * @param iSum
     * @return 校验位
     */
    public static String getCheckCode18(int iSum) {
        String code = "";
        switch (iSum % 11) {
            case 10:
                code = "2";
                break;
            case 9:
                code = "3";
                break;
            case 8:
                code = "4";
                break;
            case 7:
                code = "5";
                break;
            case 6:
                code = "6";
                break;
            case 5:
                code = "7";
                break;
            case 4:
                code = "8";
                break;
            case 3:
                code = "9";
                break;
            case 2:
                code = "x";
                break;
            case 1:
                code = "0";
                break;
            case 0:
                code = "1";
                break;
        }
        return code;
    }

    /**
     * 根据身份编号获取年龄
     *
     * @param idCard 身份编号
     * @return 年龄
     */

    public static int getCardAge(String idCard) {
        int age = 0;
        if (idCard.length() == 15) {
            idCard = card15to18(idCard);
        }
        boolean isCard = isCard18(idCard);
        if (!isCard) {
            return age;
        }
        String year = idCard.substring(6, 10);
        Calendar cal = Calendar.getInstance();
        int iCurrYear = cal.get(Calendar.YEAR);
        age = iCurrYear - Integer.valueOf(year);
        return age;
    }

    /**
     * 根据身份编号获取生日
     *
     * @param idCard 身份编号
     * @return 生日(yyyyMMdd)
     */
    public static String getCardBirth(String idCard) {
        if (TextUtils.isEmpty(idCard)) {
            return "";
        }
        if (idCard.length() == 15) {
            idCard = card15to18(idCard);
        }
        boolean isCard = isCard18(idCard);
        if (!isCard) {
            return "";
        }
        return idCard.substring(6, 14);
    }


    /**
     * 根据身份编号获取性别
     *
     * @param idCard 身份编号
     * @return 性别(M-男，F-女，N-未知)
     */

    public static String getCradGender(String idCard) {
        String gender = "未知";
        if (TextUtils.isEmpty(idCard)) {
            return gender;
        }
        if (idCard.length() == 15) {
            idCard = card15to18(idCard);
        }
        boolean isCard = isCard18(idCard);
        if (!isCard) {
            return "";
        }
        String sCardNum = idCard.substring(16, 17);
        if (Integer.parseInt(sCardNum) % 2 != 0) {
            gender = "男";
        } else {
            gender = "女";
        }
        return gender;
    }

    /**
     * 根据身份编号获取户籍省份
     *
     * @param idCard 身份编码
     * @return 省级编码。
     */

    public static String getCardProvince(String idCard) {
        if (TextUtils.isEmpty(idCard)) {
            return "";
        }
        int len = idCard.length();
        String provinceId = "";
        if (len == 15 || len == 18) {
            provinceId = idCard.substring(0, 2);
        }
        String ProvinceNme = provinceCodes.get(provinceId);
        return ProvinceNme;
    }

    /**
     * 验证是否是一个正常的时间
     *
     * @param iYear  待验证日期(年)
     * @param iMonth 待验证日期(月 1-12)
     * @param iDate  待验证日期(日)
     * @return 是否有效
     */

    private static boolean isDate(int iYear, int iMonth, int iDate) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int datePerMonth;
        if (iYear < MIN || iYear >= year) {
            return false;
        }
        if (iMonth < 1 || iMonth > 12) {
            return false;
        }
        switch (iMonth) {
            case 4:
            case 6:
            case 9:
            case 11:
                datePerMonth = 30;
                break;
            case 2:
                boolean dm = ((iYear % 4 == 0 && iYear % 100 != 0) || (iYear % 400 == 0)) && (iYear > MIN && iYear < year);
                datePerMonth = dm ? 29 : 28;
                break;
            default:
                datePerMonth = 31;
        }
        return (iDate >= 1) && (iDate <= datePerMonth);
    }
}
